package array;

/**
 * @see https://leetcode-cn.com/problems/plus-one/
 * @author hgvgh
 * @version 1.0 加1
 * @description
 * @date 2022/1/2
 */
public class PlusOne {

  public static void main(String[] args) {
    int[] ints = plusOne(new int[]{1, 2, 3});
    printArr(ints);
    ints = plusOne(new int[]{8, 9, 9});
    printArr(ints);
    ints = plusOne(new int[]{9, 9, 9});
    printArr(ints);
    ints = plusOne(new int[]{0});
    printArr(ints);
  }

  private static void printArr(int[] ints) {
    System.out.println("=====================");
    for (int i = 0; i < ints.length; i++) {
      System.out.println(ints[i]);
    }
  }

  public static int[] plusOne(int[] digits) {
    for (int i = digits.length - 1; i >= 0; i--) {
      int last = digits[i];
      if (i == digits.length - 1) {
        last = digits[i] + 1;
        digits[i] = last;
      }
      //如果自己位是10，则将自己位数变为0，前一位加1
      if (last == 10 && i > 0) {
        digits[i] = 0;
        digits[i - 1] += 1;
      }
      //首位为10的情况
      if(last == 10 && i == 0) {
        int [] newArr = new int[digits.length + 1];
        newArr[0] = 1;
        newArr[1] = 0;
        for (int j = 1; j < digits.length - 1; j++) {
          newArr[j + 1] = digits[j];
        }
        return newArr;
      }
    }
    return digits;
  }

}
